package com.baozun.houji.goods.fragment

import android.os.Bundle
import android.view.View
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.launcher.ARouter
import com.baozhun.mall.common.adapter.HomeCategoryGoodsAdapter
import com.baozhun.mall.common.arouter.RoutePath
import com.baozhun.mall.common.base.BaseFragment
import com.baozhun.mall.common.ext.loadArrayListData
import com.baozhun.mall.common.ext.showToast
import com.baozhun.mall.common.model.bean.ApiPagerResponse
import com.baozhun.mall.common.model.bean.ClassifyInfo
import com.baozhun.mall.common.model.bean.GoodsInfoBean
import com.baozhun.mall.common.model.enums.GoodsType
import com.baozhun.mall.common.util.AppUtil
import com.baozhun.mall.common.util.Constants
import com.baozhun.mall.common.util.eventbus.EventBusUtils
import com.baozhun.mall.common.util.eventbus.EventCode
import com.baozhun.mall.common.util.eventbus.EventMessage
import com.baozhun.mall.common.widget.EmptyView
import com.baozun.houji.goods.R
import com.baozun.houji.goods.databinding.FragmentCategoryListBinding
import com.baozun.houji.goods.viewmodel.CategoryListViewModel
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.samluys.filtertab.FilterInfoBean
import com.samluys.filtertab.FilterResultBean
import com.samluys.filtertab.FilterTabConfig
import com.samluys.filtertab.listener.OnSelectResultListener
import com.scwang.smart.refresh.layout.api.RefreshLayout
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @Title：首页分类商品列表页
 * @Description：对应 CategoryPageListAdapter
 * @Author：xing.luo
 * @Since：2022/11/09
 * @Version：1.0.0
 */
class CategoryFragment : BaseFragment<CategoryListViewModel, FragmentCategoryListBinding>(),
    OnItemClickListener, OnSelectResultListener {

    private val mHomeCategoryGoodsAdapter by lazy { HomeCategoryGoodsAdapter() }
    private val mId by lazy { arguments?.getString(IS_CATEGORY_ID).toString() }
    private val mIsStaggeredGrid by lazy { arguments?.getBoolean(IS_STAGGERED_GRID) }
    private val mShowAdvertisement by lazy { arguments?.getBoolean(SHOW_ADVERTISEMENT) }
    private val mThreeLevelCategoryData by lazy { arguments?.getSerializable(THREE_LEVEL_CATEGORY) as ArrayList<ClassifyInfo> }
    private var mRefreshLayout: RefreshLayout? = null
    private var mSortType: Int? = null //1:点击量 2:余额 3:价格
    private var mSortOrder: Int? = null //升降类型 2:降序 非2为升序
    private var mCategoryViewPageSize = 1

    companion object {

        const val CLASS_VIEW_PAGER_SIZE = 8
        private const val IS_STAGGERED_GRID = "isStaggeredGrid"
        private const val IS_CATEGORY_ID = "categoryId"
        private const val THREE_LEVEL_CATEGORY = "threeLevelCategory"
        private const val SHOW_ADVERTISEMENT = "showAdvertisement"

        fun newInstance(
            categoryId: String,
            isStaggeredGrid: Boolean,
            threeLevelCategoryData: ArrayList<ClassifyInfo>?,
            showAdvertisement: Boolean = false
        ): CategoryFragment {
            val args = Bundle()
            val fragment = CategoryFragment()
            args.putString(IS_CATEGORY_ID, categoryId)
            args.putBoolean(IS_STAGGERED_GRID, isStaggeredGrid)
            args.putSerializable(THREE_LEVEL_CATEGORY, threeLevelCategoryData)
            args.putBoolean(SHOW_ADVERTISEMENT, showAdvertisement)
            fragment.arguments = args
            return fragment
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        initTopCategoryClass()
        initFilterView()
        EventBusUtils.register(this)
        mHomeCategoryGoodsAdapter?.setOnItemClickListener(this)
        mHomeCategoryGoodsAdapter?.setEmptyView(EmptyView.Builder(mActivity).build())
        mDataBinding.categoryRecycleView.adapter = mHomeCategoryGoodsAdapter
        mHomeCategoryGoodsAdapter.loadMoreModule.preLoadNumber = 10
    }

    /**
     * 初始化顶部分类
     */
    private fun initTopCategoryClass() {
        //需求变更，不显示三级分类
//        mViewModel.mShowThreeLevelCategory.value = mThreeLevelCategoryData?.isNotEmpty()
        if (mThreeLevelCategoryData.isNullOrEmpty()) return
        var classData = AppUtil.transformClassData(mThreeLevelCategoryData, CLASS_VIEW_PAGER_SIZE)
        mCategoryViewPageSize = if (classData?.size == 0) 1 else classData?.size!!
        mDataBinding.vpCategory.create(classData)
        mDataBinding.vpCategory.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                var position = if (position == mCategoryViewPageSize - 1) mCategoryViewPageSize else position
                mDataBinding.categoryIndicator.setProgress(position.toFloat() / mCategoryViewPageSize)
            }
        })
        mViewModel.mShowCategoryIndicator.value = classData.size > 1
        mDataBinding.categoryIndicator.setTotalCount(mCategoryViewPageSize)
    }

    private fun showClassifyGoodsList(classifyInfo: ClassifyInfo) {
        classifyInfo.goods_type = GoodsType.CHANNEL.type
        ARouter.getInstance().build(RoutePath.Home.CATEGORY_GOODS_LIST)
            .withSerializable(Constants.Common.BUNDLE_NAME, classifyInfo)
            .navigation()
    }

    private fun initFilterView() {
        val bean1 = FilterInfoBean("精选", FilterTabConfig.FILTER_TYPE_NO_POP, null, 1)
        val bean2 = FilterInfoBean("返现", FilterTabConfig.FILTER_TYPE_NO_POP, null, 4)
        val bean3 = FilterInfoBean("价格", FilterTabConfig.FILTER_TYPE_NO_POP_HAS_ARROW, null, 3)
        mDataBinding.filterView.addFilterItems(bean1, bean2, bean3)
        mDataBinding.filterView.setOnSelectResultListener(this)
        mDataBinding.filterView.setClickFilter(0)
    }

    override fun initData() {
        super.initData()
        mNoMoreData = false
        mViewModel.getCategoryGoodsList(true, mId)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: EventMessage<Any>) {
        if (event.eventCode == EventCode.BROWSE_GET_POINT_SUCCESS) {
            mHomeCategoryGoodsAdapter.data.find { it.goods_id == event.data.toString() }?.is_get_point = true
            mHomeCategoryGoodsAdapter.notifyDataSetChanged()
        }
    }

    override fun createObserver() {
        mViewModel.categoryGoodsInfo.observe(this) {
            mDataBinding.viewPageLoad.hidePlaceholderView()
            mRefreshLayout?.finishLoadMore()
            updateNewGoodsTips(it)
            if (mShowAdvertisement == true && it.isRefresh()) { //刷新的时候添加平台slogan
                it.data.add(0, GoodsInfoBean().apply { platform_slogan = true })
            }
            loadArrayListData(it, mHomeCategoryGoodsAdapter, null)

            if (mRefreshLayout != null && mViewModel.mCurrentPage != 1 && it.data.isNullOrEmpty()) {
                mNoMoreData = true
                showToast(com.baozhun.mall.res.R.string.no_data_hint)
            }
        }
    }

    /**
     * 更新新品上架提示状态
     */
    private fun updateNewGoodsTips(it: ApiPagerResponse<java.util.ArrayList<GoodsInfoBean>>?) {

        if (it?.new_goods_count != null && it.new_goods_count!! > 0) {
            mDataBinding.tvNewGoodsPublishTip.visibility = View.VISIBLE
            mDataBinding.tvNewGoodsPublishTip.text = String.format(getString(com.baozhun.mall.res.R.string.new_goods_tip_format), it?.new_goods_count)
        } else {
            mDataBinding.tvNewGoodsPublishTip.visibility = View.GONE
        }
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {

    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        mRefreshLayout = refreshLayout
        if (mNoMoreData) {
            showToast(com.baozhun.mall.res.R.string.no_data_hint)
            refreshLayout?.finishLoadMore()
            return
        }
        mViewModel.getCategoryGoodsList(false, mId, mSortType, mSortOrder, refreshLayout)
    }

    override fun onSelectResult(resultBean: FilterResultBean?) {
        mSortType = resultBean?.itemId// 1、推荐 2、销量 3、价格 4、返现
        mSortOrder = if (resultBean?.isArrowUp == true) 1 else 2
        mDataBinding.viewPageLoad.showPlaceholderView()
        mViewModel.getCategoryGoodsList(true, mId, mSortType, mSortOrder, mRefreshLayout)
    }

    override fun onSelectResultList(resultBeans: MutableList<FilterResultBean>?) {

    }

    override fun useFragmentViewModelStoreOwner(): Boolean {
        return true
    }

}